<template>
    <div class="app-container">

        <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
            <el-col :span="6">
                <el-form-item label="客户名称:" prop="primaryCustomerName">
                    <el-input maxlength="30" v-model="queryParams.primaryCustomerName" clearable placeholder="请输入客户名称"></el-input>
                </el-form-item>
            </el-col>
        </SearchContent>

        <div class="card-wrap card-padding">
            <div class="table-title-wrap justify-end">
                <el-button type="primary" size="mini" @click="handleAdd"
                           v-hasPermi="['memberClue:shareMemberList:add']">新增
                </el-button>
            </div>

            <table-page :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @setSizeCurrent="getList">
                <!-- 操作插槽 -->
                <template slot="tableColAc">
                    <el-table-column label="操作" min-width="115" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <e-button size="mini" type="text" @click="handleUpdate(scope.row)"
                                      v-hasPermi="['memberClue:shareMemberList:edit']">编辑
                            </e-button>
                            <e-button size="mini" type="text" @click="handleDelete(scope.row)"
                                      v-hasPermi="['memberClue:shareMemberList:delete']">删除
                            </e-button>
                            <e-button size="mini" type="text" @click="handleDetail(scope.row)"
                                      v-hasPermi="['memberClue:shareMemberList:view']">查看
                            </e-button>
                        </template>
                    </el-table-column>
                </template>
                <!-- 普通列插槽 -->
                <template slot="tableCol">
                    <el-table-column show-overflow-tooltip label="业务范围" min-width="90" align="center" prop="businessScopeCode">
                        <template slot-scope="scope">
                            <dict-tag
                                :options="dict.type.business_scope"
                                :value="scope.row.businessScopeCode"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip label="客户编码" min-width="190" align="center" prop="customerCode">
                        <template v-slot="{row}">
                            {{ row.customerCode|filterNull }}
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip label="客户名称" min-width="130" align="center" prop="customerName">
                        <template v-slot="{row}">
                            {{ row.customerName|filterNull }}
                        </template>
                    </el-table-column>

                    <el-table-column show-overflow-tooltip label="联系电话" min-width="130" align="center" prop="customerPhone">
                        <template v-slot="{row}">
                            {{ row.customerPhone|filterNull }}
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip show-overflow-tooltip label="共用额度客户" min-width="190" align="center" prop="secondaryCustomerName">
                        <template v-slot="{row}">
                            {{ row.secondaryCustomerName|filterNull }}
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip label="创建人" min-width="130" align="center" prop="createBy">
                        <template v-slot="{row}">
                            {{ row.createBy|filterNull }}
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip label="创建时间" min-width="150" align="center" prop="updateTime">
                        <template v-slot="{row}">
                            {{ row.updateTime|filterNull }}
                        </template>
                    </el-table-column>
                </template>
            </table-page>

        </div>

        <!--    共用额度客户-->
        <el-dialog title="共用额度客户" :visible.sync="publicOpen" append-to-body width="45%">
            <el-form ref="publicForm" :rules="publicRules" :model="publicForm" label-width="120px">

                <el-row>
                    <el-col :span="20">
                        <el-form-item label="客户名称:" prop="primaryCustomerId">
                            <el-select v-model="publicForm.primaryCustomerId"
                                       @change="memberSel"
                                       clearable filterable style="width: 100%">
                                <template v-for="dict in memberList">
                                    <el-option :label="dict.customerName" :value="dict.customerId" :key="dict.customerId"></el-option>
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="共用额度客户:" prop="secondaryCustomerIdList">
                            <el-select v-model="publicForm.secondaryCustomerIdList"
                                       @change="shareMemberSel"
                                       multiple clearable filterable style="width: 100%">
                                <template v-for="dict in shareMemberList">
                                    <el-option :label="dict.customerName" :value="dict.customerId" :key="dict.customerId"></el-option>
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="20">
                        <el-form-item label="描述:" prop="remark">

                            <el-input v-model="publicForm.remark"
                                      type="textarea" maxlength="400"
                                      :rows="2"
                                      clearable placeholder="请输入描述"></el-input>

                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div slot="footer">
                <el-button @click="publicCancel">{{ isNew ? '取消' : '关闭' }}</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="isNew">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import SearchContent from "@/components/SearchContent/index.vue";
import {getCustomerList, quotaSharing, quotaSharingDelete, quotaSharingList, quotaSharingAdd} from "@/api/memberManage/memberList";

export default {
    name:"ShareMemberList",
    components: {
        SearchContent
    },
    dicts: ['business_yes_no', 'business_scope'],
    data() {
        return {
            //按钮loading
            buttonLoading: false,
            publicLoading: false,
            // 遮罩层
            loading: true,
            isNew: true,
            // 弹出层标题
            title: "",
            publicOpen: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                primaryCustomerName:null
            },
            total: 0,
            dataList: [],
            publicForm: {
                secondaryCustomerIdList:[]
            },
            // 表单校验
            publicRules: {
                primaryCustomerId: [
                    {required: true, message: "客户名称不能为空", trigger: "change"}
                ],
                secondaryCustomerIdList: [
                    {required: true, type:'array', message: "共用额度客户不能为空", trigger: "change"}
                ],
            },
            memberList:[],
            shareMemberList:[]
        };
    },
    created() {
        this.getMember()
        this.getList()
    },
    activated() {
        this.getMember()
        this.getList()
    },
    methods: {
        async memberSel(val){
            console.log('memberSel', val)
            const selMember = this.memberList.find(item=>item.customerId==val)
            if(selMember){
                this.publicForm.primaryCustomerName = selMember?.customerName??null
                this.shareMemberList = this.memberList.filter(item=>item.customerId!=selMember.customerId)

                const detail = await this.getMemberDetail(selMember.customerId)

                if(detail && detail.length > 0){
                    // this.publicForm.secondaryCustomerIdList = detail?.secondaryCustomerId?.split(",")??[]
                    this.publicForm.secondaryCustomerIdList = detail.map(item=>item.secondaryCustomerId)
                    this.publicForm.quotaSharingId = detail[0].quotaSharingId
                }else {
                    this.publicForm.secondaryCustomerIdList = []
                    this.publicForm.quotaSharingId = null
                }
                console.log('detail', detail)
            }else {
                this.publicForm.primaryCustomerName = null
                this.publicForm.secondaryCustomerIdList = []
                this.publicForm.quotaSharingId = null
                this.shareMemberList = this.memberList
            }
        },

        async getMemberDetail(customerId){
            return quotaSharing(customerId).then(res=>{
                return res.data
            })
        },

        shareMemberSel(val){
            console.log('shareMemberSel', val)

            if(val && val.length>0){
                this.publicForm.secondaryCustomerIdList = val
                this.publicForm.secondaryCustomerNameList = []
                this.publicForm.secondaryCustomerNameList =
                    this.shareMemberList.filter(item=>val.indexOf(item.customerId)>-1)
                        .map(item=>item.customerName)
            }else {
                this.publicForm.secondaryCustomerIdList = []
                this.publicForm.secondaryCustomerNameList = []
            }


        },
        getMember(){
            getCustomerList({
                pageNum: 1,
                pageSize: 1000000,
            }).then(res => {
                if (res.code == "200") {
                    this.memberList = res.rows
                    this.shareMemberList = res.rows
                }
            });

        },
        /** 查询测试单表列表 */
        getList() {
            this.loading = true;

            quotaSharingList(this.queryParams).then(res => {
                if (res.code == "200") {
                    const {rows, total} = res
                    this.dataList = rows
                    this.total = total
                    this.loading = false;
                }
            });

        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 取消按钮
        publicCancel() {
            this.publicOpen = false;
            this.publicForm = {
                secondaryCustomerIdList:[]
            }
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                tagName: "",
                remark: "",
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                primaryCustomerName:null
            },
            // this.resetForm("queryForm");
            this.handleQuery();
        },

        /** 新增操作 */
        handleAdd() {
            this.publicOpen = true
        },

        handleDetail(row) {
          // this.$router.push({
          this._toPage({
                name: 'ShareMemberDetail',
                query: {
                    quotaSharingId: row.quotaSharingId,
                    primaryCustomerId: row.primaryCustomerId,
                    primaryCustomerName: row.primaryCustomerName,
                    remark: row.remark,
                    type:'detail',
                    pageType:'共用额度客户详情'}
            })
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
          // this.$router.push({
          this._toPage({
                name: 'ShareMemberDetail',
                query: {quotaSharingId: row.quotaSharingId,
                        primaryCustomerId: row.primaryCustomerId,
                        primaryCustomerName: row.primaryCustomerName,
                        remark: row.remark,
                        type:'edit',
                        pageType:'编辑共用额度客户'}
            })
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            console.log('row', row)
            this.$modal.confirm('确定删除？').then(() => {
                this.loading = true;
                return quotaSharingDelete(row.quotaSharingId);
            }).then(() => {
                this.loading = false;
                this.handleQuery();
                this.$modal.msgSuccess("删除成功");
            }).finally(() => {
                this.loading = false;
            });

        },

        /** 提交按钮 */
        submitForm() {
            this.$refs["publicForm"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    quotaSharingAdd(this.publicForm).then(response => {
                        this.publicForm = {
                            secondaryCustomerIdList:[]
                        }
                        this.$modal.msgSuccess("新增成功");
                        this.publicOpen = false;
                        this.getList();
                    }).finally(() => {
                        this.buttonLoading = false;
                    });
                }
            });
        },

    }
};
</script>


<style lang="scss" scoped>
.pagination-container {
    padding: 0 20px 50px !important;
}


.form-dialog {
    ::v-deep .el-dialog__header {
        padding: 10px 20px;
        border-bottom: 1px solid #DCDFE6;

        .el-dialog__headerbtn {
            top: 15px;
        }
    }

    .box-card {
        margin-bottom: 20px;

        .card-title {
            font-size: 16px;
            position: relative;
            margin-left: 8px;
            padding: 0;
        }

        .card-title::after {
            content: '';
            width: 4px;
            height: 18px;
            background-color: aqua;
            display: block;
            position: absolute;
            left: -12px;
            top: 2px;
        }
    }

}
</style>
